package com.primb.bench.project.home.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.primb.baselibs.util.FormatUtils;
import com.primb.baselibs.view.AutoToolbar;
import com.primb.bench.R;
import com.primb.bench.base.SwipeBaseActivity;
import com.primb.bench.common.constant.AppConstant;
import com.primb.bench.common.dialog.SelectListDialog;
import com.primb.bench.project.home.contract.AddInfoContract;
import com.primb.bench.project.home.entity.ClientInfoEntity;
import com.primb.bench.project.home.entity.EnsureInfoEntity;
import com.primb.bench.project.home.entity.KeyEntity;
import com.primb.bench.project.home.entity.LoanInfoEntity;
import com.primb.bench.project.home.entity.LogoInfoEntity;
import com.primb.bench.project.home.entity.TaxInfoEntity;
import com.primb.bench.project.home.presenter.AddInfoPresenterImpl;
import com.suke.widget.SwitchButton;

import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Chen on 2017/5/3.
 * 功能描述：
 */

public class AddInfoActivity extends SwipeBaseActivity implements AddInfoContract.View {

    @BindView(R.id.title_bar)
    TextView titleBar;
    @BindView(R.id.tool_bar)
    AutoToolbar toolBar;
    @BindView(R.id.scroll_loan)
    ScrollView scrollLoan;
    @BindView(R.id.iv_top)
    ImageView ivTop;
    @BindView(R.id.tv_customer_number)
    TextView tvCustomerNumber;
    @BindView(R.id.et_customer_name)
    EditText etCustomerName;
    @BindView(R.id.tv_customer_type)
    TextView tvCustomerType;
    @BindView(R.id.tv_customer_credit)
    TextView tvCustomerCredit;
    @BindView(R.id.iv_customer_credit)
    ImageView ivCustomerCredit;
    @BindView(R.id.tv_customer_size)
    TextView tvCustomerSize;
    @BindView(R.id.iv_customer_size)
    ImageView ivCustomerSize;
    @BindView(R.id.tv_contribution_number)
    TextView tvContributionNumber;
    @BindView(R.id.et_rate_adjust)
    EditText etRateAdjust;
    @BindView(R.id.layout_info_customer)
    LinearLayout layoutInfoCustomer;
    @BindView(R.id.tv_loan_type)
    TextView tvLoanType;
    @BindView(R.id.iv_loan_type)
    ImageView ivLoanType;
    @BindView(R.id.et_loan_money)
    EditText etLoanMoney;
    @BindView(R.id.tv_condition_date_unit)
    TextView tvLoanDate;
    @BindView(R.id.tv_loan_business_type)
    TextView tvLoanBusinessType;
    @BindView(R.id.iv_loan_business_type)
    ImageView ivLoanBusinessType;
    @BindView(R.id.tv_loan_industry)
    TextView tvLoanIndustry;
    @BindView(R.id.iv_loan_industry)
    ImageView ivLoanIndustry;
    @BindView(R.id.tv_loan_rate_type)
    TextView tvLoanRateType;
    @BindView(R.id.iv_loan_rate_type)
    ImageView ivLoanRateType;
    @BindView(R.id.layout_info_loan)
    LinearLayout layoutInfoLoan;
    @BindView(R.id.tv_ensure_main_type)
    TextView tvEnsureMainType;
    @BindView(R.id.iv_ensure_main_type)
    ImageView ivEnsureMainType;
    @BindView(R.id.tv_ensure_info)
    TextView tvEnsureInfo;
    @BindView(R.id.tv_ensure_concreteness_type)
    TextView tvEnsureConcretenessType;
    @BindView(R.id.iv_ensure_concreteness_type)
    ImageView ivEnsureConcretenessType;
    @BindView(R.id.layout_info_ensure)
    LinearLayout layoutInfoEnsure;
    @BindView(R.id.layout_ensure_concreteness)
    RelativeLayout layoutEnsureConcreteness;
    @BindView(R.id.iv_loan_date)
    ImageView ivLoanDate;
    @BindView(R.id.layout_add_tax)
    LinearLayout layoutAddTax;
    @BindView(R.id.et_tax_vat)
    EditText etTaxVat;
    @BindView(R.id.tv_tax_income)
    TextView tvTaxIncome;
    @BindView(R.id.tv_customer_all_profit)
    TextView tvCustomerAllProfit;
    @BindView(R.id.tv_customer_all_contribution)
    TextView tvCustomerAllContribution;
    @BindView(R.id.tv_customer_used_contribution)
    TextView tvCustomerUsedContribution;
    @BindView(R.id.sw_customer_is_contribution)
    SwitchButton tvCustomerIsContribution;
    @BindView(R.id.et_loan_date)
    EditText etLoanDate;
    @BindView(R.id.tv_add_logo_serial_number)
    TextView tvAddLogoSerialNumber;
    @BindView(R.id.tv_add_logo_part)
    TextView tvAddLogoPart;
    @BindView(R.id.tv_add_logo_protocol_number)
    TextView tvAddLogoProtocolNumber;
    @BindView(R.id.tv_add_logo_manager_name)
    TextView tvAddLogoManagerName;
    @BindView(R.id.tv_add_logo_manager_number)
    TextView tvAddLogoManagerNumber;
    @BindView(R.id.tv_add_logo_date)
    TextView tvAddLogoDate;
    @BindView(R.id.layout_info_logo)
    LinearLayout layoutInfoLogo;
    @BindView(R.id.tv_ensure_money_finance)
    TextView tvEnsureMoneyFinance;
    @BindView(R.id.tv_ensure_money_debt)
    TextView tvEnsureMoneyDebt;
    @BindView(R.id.tv_ensure_money_house)
    TextView tvEnsureMoneyHouse;
    @BindView(R.id.tv_ensure_money_other)
    TextView tvEnsureMoneyOther;
    @BindView(R.id.tv_ensure_money_good)
    TextView tvEnsureMoneyGood;
    @BindView(R.id.tv_ensure_money_bad)
    TextView tvEnsureMoneyBad;
    @BindView(R.id.tv_loan_repayment_type)
    TextView tvLoanRepaymentType;
    private AddInfoPresenterImpl mPresenter;
    private int type;
    private Object info;
    private String clientType;
    private String priceId;
    private boolean isShowKey = false;

    @Override
    protected void onBaseIntent() {
        Intent intent = getIntent();
        type = intent.getIntExtra("code", -1);
        info = getIntent().getParcelableExtra("info");
        clientType = intent.getStringExtra("clientType");
        priceId = intent.getStringExtra("priceId");
    }

    @Override
    protected int onBaseLayoutId(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_add_loan;
    }

    @Override
    protected void onBaseBindView() {
        ivTop.setImageResource(R.mipmap.save_icon);
        ivTop.setVisibility(View.VISIBLE);
        toolBar.setNavigationOnClickListener(v -> {
            if (type != AppConstant.LOAN_ENSURE_REQUEST)
                AddInfoActivity.this.finish();
            else {
                if (!mPresenter.isCheckEmpty(type)) {
                    setResultToCalculate(type, mPresenter.getInfoEntity(type));
                } else {
                    showError("请完善信息后保存");
                }
            }
        });

        tvCustomerIsContribution.setOnCheckedChangeListener((view, isChecked) -> mPresenter.clientInfoEntity.setCustomerIsContribution(isChecked ? "是" : "否"));
        etCustomerName.setEnabled(false);
    }

    @Override
    protected void onLoadData() {
        mPresenter = new AddInfoPresenterImpl(this, this);
        mPresenter.start();
        mPresenter.setClientType(clientType);
        mPresenter.setPriceId(priceId);
//        KeyboardWatcher keyboardWatcher = new KeyboardWatcher(this);
//        keyboardWatcher.setListener(new KeyboardWatcher.OnKeyboardToggleListener() {
//            @Override
//            public void onKeyboardShown(int keyboardSize) {
//                isShowKey = true;
//            }
//
//            @Override
//            public void onKeyboardClosed() {
//                isShowKey = false;
//                if (etLoanMoney.isFocusable()) {
//                    String money = etLoanMoney.getText().toString();
//                    if (null != money && !money.equals("")) {
//                        try {
//                            Double integer = Double.valueOf(money);
//                            String format2Double = FormatUtils.format2Double(integer);
//                            etLoanMoney.setText(format2Double);
//                        } catch (Exception e) {
//                            showError("担保金额格式有误");
//                        }
//                    }
//                }
//            }
//        });
//
//        etLoanMoney.setOnFocusChangeListener(new View.OnFocusChangeListener() {
//            @Override
//            public void onFocusChange(View v, boolean hasFocus) {
//                if (isShowKey && !hasFocus){
//                    String money = etLoanMoney.getText().toString();
//                    if (null != money && !money.equals("")) {
//                        try {
//                            etLoanMoney.setText(money.replace(",", ""));
//                        } catch (Exception e) {
//
//                        }
//                    }
//                }
//            }
//        });
    }

    @Override
    public void showLoading() {
        showLoadingDialog("加载中");
    }

    @Override
    public void hideLoading() {
        hideLoadingDialog();
    }

    @Override
    public void showError(String msg) {
        showToast(msg);
    }

    @Override
    public void showLayoutForType() {
        hideLayout();
        switch (type) {
            case AppConstant.LOAN_LOGO_REQUEST:
                titleBar.setText("定价信息");
                layoutInfoLogo.setVisibility(View.VISIBLE);
                setLogoEntityToView(((LogoInfoEntity) info));
                break;
            case AppConstant.LOAN_CUSTOMER_REQUEST:
                titleBar.setText("客户信息");
                layoutInfoCustomer.setVisibility(View.VISIBLE);
                setClientEntityToView(((ClientInfoEntity) info));
                break;
            case AppConstant.LOAN_LOAN_REQUEST:
                titleBar.setText("贷款信息");
                layoutInfoLoan.setVisibility(View.VISIBLE);
                setLoanEntityToView(((LoanInfoEntity) info));
                break;
            case AppConstant.LOAN_ENSURE_REQUEST:
                titleBar.setText("担保信息");
                layoutInfoEnsure.setVisibility(View.VISIBLE);
                setEnsureEntityToView(((EnsureInfoEntity) info));
                break;
            case AppConstant.LOAN_TAX_REQUEST:
                titleBar.setText("税务信息");
                layoutAddTax.setVisibility(View.VISIBLE);
                setTaxEntityToView(((TaxInfoEntity) info));
                break;
        }
    }

    @Override
    public void hideLayout() {
        layoutInfoCustomer.setVisibility(View.GONE);
        layoutInfoLoan.setVisibility(View.GONE);
        layoutInfoEnsure.setVisibility(View.GONE);
        layoutInfoLogo.setVisibility(View.GONE);
    }

    @Override
    public void setResultToCalculate(int requestCode, Object entity) {
        Intent intent = new Intent();
        switch (requestCode) {
            case AppConstant.LOAN_LOGO_REQUEST:
                intent.putExtra("info", (LogoInfoEntity) entity);
                setResult(AppConstant.LOAN_LOGO_RESULT, intent);
                break;
            case AppConstant.LOAN_CUSTOMER_REQUEST:
                intent.putExtra("info", (ClientInfoEntity) entity);
                setResult(AppConstant.LOAN_CUSTOMER_RESULT, intent);
                break;
            case AppConstant.LOAN_LOAN_REQUEST:
                intent.putExtra("info", (LoanInfoEntity) entity);
                setResult(AppConstant.LOAN_LOAN_RESULT, intent);
                break;
            case AppConstant.LOAN_ENSURE_REQUEST:
                intent.putExtra("info", (EnsureInfoEntity) entity);
                setResult(AppConstant.LOAN_ENSURE_RESULT, intent);
                break;
            case AppConstant.LOAN_TAX_REQUEST:
                intent.putExtra("info", (TaxInfoEntity) entity);
                setResult(AppConstant.LOAN_TAX_RESULT, intent);
                break;
        }
        this.finish();
    }

    @Override
    public void getEnsureInfo(int requestCode) {
        Intent intent = new Intent(AddInfoActivity.this, LoanEnsureActivity.class);
        intent.putExtra("info", ((EnsureInfoEntity) info));
        intent.putExtra("priceId", priceId);
        startActivityForResult(intent, requestCode);
    }

    @Override
    public void setDataToClientEntity(ClientInfoEntity entity) {
        entity.setCustomerName(etCustomerName.getText().toString());
        entity.setCustomerAdjustRate(etRateAdjust.getText().toString());
    }

    @Override
    public void setDataToLoanEntity(LoanInfoEntity entity) {
        entity.setLoanMoney(etLoanMoney.getText().toString());
        entity.setLoanDate(etLoanDate.getText().toString());
    }

    @Override
    public void setDataToTaxEntity(TaxInfoEntity entity) {
        entity.setTaxVat(etTaxVat.getText().toString());
    }

    private void setLogoEntityToView(LogoInfoEntity entity) {
        if (entity != null) {
            mPresenter.logoInfoEntity = entity;
            tvAddLogoDate.setText(FormatUtils.DATE_FORMAT.format(new Date()));
            tvAddLogoManagerName.setText(entity.getLogoManagerName());
            tvAddLogoManagerNumber.setText(entity.getLogoManagerNum());
            tvAddLogoPart.setText(entity.getLogoPart());
            tvAddLogoProtocolNumber.setText(entity.getLogoProtocolNum());
            tvAddLogoSerialNumber.setText(entity.getLogoNumber());
        }
    }

    @Override
    public void setClientEntityToView(ClientInfoEntity entity) {
        if (entity != null) {
            mPresenter.clientInfoEntity = entity;
            tvCustomerNumber.setText(entity.getCustomerNum());
            tvCustomerSize.setText(entity.getCustomerSize());
            tvCustomerCredit.setText(entity.getCustomerCredit());
            tvCustomerType.setText(entity.getCustomerType());
            etCustomerName.setText(entity.getCustomerName());
            etRateAdjust.setText(entity.getCustomerAdjustRate());
            etRateAdjust.setEnabled(false);
            tvContributionNumber.setText(entity.getCustomerContributionNum());
            tvCustomerAllContribution.setText(entity.getCustomerAllContribution());
            tvCustomerAllProfit.setText(entity.getCustomerAllProfit());
            if (entity.getCustomerIsContribution().equals("是"))
                tvCustomerIsContribution.setChecked(true);
            else
                tvCustomerIsContribution.setChecked(false);
            tvCustomerUsedContribution.setText(entity.getCustomerUsedContribution());
        }
    }

    @Override
    public void setLoanEntityToView(LoanInfoEntity entity) {
        if (entity != null) {
            mPresenter.loanInfoEntity = entity;
            tvLoanType.setText(entity.getLoanType());
            etLoanMoney.setText(entity.getLoanMoney());
            etLoanDate.setText(entity.getLoanDate());
            tvLoanDate.setText(entity.getLoanDateUnit());
            tvLoanBusinessType.setText(entity.getLoanBusinessType());
            tvLoanRepaymentType.setText(entity.getLoanRepayment());
            tvLoanIndustry.setText(entity.getLoanIndustry() == null || entity.getLoanIndustry().equals("") ? "请选择行业投向" : entity.getLoanIndustry());
            tvLoanRateType.setText(entity.getLoanRateType() == null || entity.getLoanRateType().equals("") ? "请选择利率类型" : entity.getLoanRateType());
        } else {
            info = mPresenter.ensureInfoEntity;
        }
    }

    @Override
    public void setEnsureEntityToView(EnsureInfoEntity entity) {
        if (entity != null) {
            mPresenter.ensureInfoEntity = entity;
            tvEnsureMainType.setText(entity.getEnsureMainType());
            tvEnsureConcretenessType.setText(entity.getEnsureConcretenessType());
            if (!entity.getEnsureMainType().equals("信用")) {
                tvEnsureInfo.setVisibility(View.VISIBLE);
            } else {
                tvEnsureInfo.setVisibility(View.GONE);
            }

            if (entity.getEnsureMainType().equals("保证")) {
                layoutEnsureConcreteness.setVisibility(View.VISIBLE);
            } else {
                layoutEnsureConcreteness.setVisibility(View.GONE);
            }
            tvEnsureMoneyFinance.setText(FormatUtils.format2Double(entity.getLnFinImpawnAmt()));
            tvEnsureMoneyHouse.setText(FormatUtils.format2Double(entity.getLnPropertyAmt()));
            tvEnsureMoneyDebt.setText(FormatUtils.format2Double(entity.getLnAcctRecvAmt()));
            tvEnsureMoneyOther.setText(FormatUtils.format2Double(entity.getLnOthMortAmt()));
            tvEnsureMoneyGood.setText(FormatUtils.format2Double(entity.getHighGuarantee()));
            tvEnsureMoneyBad.setText(FormatUtils.format2Double(entity.getCommonGuarantee()));
        } else {
            info = mPresenter.ensureInfoEntity;
//            setEnsureEntityToView((EnsureInfoEntity) info);
            tvEnsureMoneyFinance.setText("0");
            tvEnsureMoneyHouse.setText("0");
            tvEnsureMoneyDebt.setText("0");
            tvEnsureMoneyOther.setText("0");
            tvEnsureMoneyGood.setText("0");
            tvEnsureMoneyBad.setText("0");
        }
    }

    @Override
    public void setTaxEntityToView(TaxInfoEntity entity) {
        if (entity != null) {
            mPresenter.taxInfoEntity = entity;
            etTaxVat.setText(entity.getTaxVat());
            tvTaxIncome.setText(entity.getTaxIncome());
        } else {
            info = mPresenter.ensureInfoEntity;
        }
    }

    @Override
    public SelectListDialog showPickerDialog(int code) {
        SelectListDialog listDialog = new SelectListDialog();
        listDialog.setListener((adapter, v, position) -> {
            setDataToView(code, listDialog.getDataList().get(position));
            mPresenter.handleInfoForList(code, listDialog.getDataList().get(position));
            listDialog.dismiss();
        });
        listDialog.show(getSupportFragmentManager());
        return listDialog;
    }

    @Override
    public void setDataToView(int code, KeyEntity keyEntity) {
        switch (code) {
            case AppConstant.ADD_CUSTOMER_TYPE:
                tvCustomerType.setText(keyEntity.getKey());
                break;
            case AppConstant.ADD_CUSTOMER_CREDIT:
                tvCustomerCredit.setText(keyEntity.getKey());
                break;
            case AppConstant.ADD_CUSTOMER_SIZE:
                tvCustomerSize.setText(keyEntity.getKey());
                break;
            case AppConstant.ADD_LOAN_TYPE:
                tvLoanType.setText(keyEntity.getKey());
                break;
            case AppConstant.ADD_LOAN_REPAYMENT_TYPE:
                tvLoanRepaymentType.setText(keyEntity.getKey());
                break;
            case AppConstant.ADD_LOAN_DATE:
                tvLoanDate.setText(keyEntity.getKey());
                break;
            case AppConstant.ADD_LOAN_BUSINESS_TYPE:
                tvLoanBusinessType.setText(keyEntity.getKey());
                break;
            case AppConstant.ADD_LOAN_INDUSTRY:
                tvLoanIndustry.setText(keyEntity.getKey());
                break;
            case AppConstant.ADD_LOAN_RATE_TYPE:
                tvLoanRateType.setText(keyEntity.getKey());
                break;
            case AppConstant.ADD_ENSURE_MAIN_TYPE:
                tvEnsureMainType.setText(keyEntity.getKey());
                if (!keyEntity.getKey().equals("保证")) {
                    layoutEnsureConcreteness.setVisibility(View.GONE);
                } else {
                    layoutEnsureConcreteness.setVisibility(View.VISIBLE);
                }
                if (!keyEntity.getKey().equals("信用")) {
                    tvEnsureInfo.setVisibility(View.VISIBLE);
                } else {
                    tvEnsureInfo.setVisibility(View.GONE);
                }
                tvEnsureConcretenessType.setText("请选择具体担保方式");
                break;
            case AppConstant.ADD_ENSURE_CONCRETENESS:
                tvEnsureConcretenessType.setText(keyEntity.getKey());
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == AppConstant.ENSURE_OBJECT_INFO && resultCode == AppConstant.ENSURE_OBJECT_RESULT) {
            EnsureInfoEntity info = data.getParcelableExtra("info");
            ((EnsureInfoEntity) this.info).setLnFinImpawnAmt(info.getLnFinImpawnAmt());
            ((EnsureInfoEntity) this.info).setLnPropertyAmt(info.getLnPropertyAmt());
            ((EnsureInfoEntity) this.info).setLnAcctRecvAmt(info.getLnAcctRecvAmt());
            ((EnsureInfoEntity) this.info).setLnOthMortAmt(info.getLnOthMortAmt());
            ((EnsureInfoEntity) this.info).setCommonGuarantee(info.getCommonGuarantee());
            ((EnsureInfoEntity) this.info).setHighGuarantee(info.getHighGuarantee());

            setEnsureEntityToView(info);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mPresenter.onRecycle();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && AppConstant.LOAN_ENSURE_REQUEST == type) {
            if (!mPresenter.isCheckEmpty(type)) {
                setResultToCalculate(type, mPresenter.getInfoEntity(type));
            } else {
                showError("请完善信息后保存");
            }
            return false;
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }

    @OnClick({R.id.iv_top, R.id.tv_customer_type, R.id.tv_customer_credit, R.id.tv_loan_type, R.id.tv_loan_repayment_type,
            R.id.tv_loan_business_type, R.id.tv_loan_industry, R.id.tv_loan_rate_type, R.id.tv_ensure_main_type,
            R.id.tv_ensure_concreteness_type, R.id.tv_condition_date_unit, R.id.tv_ensure_info, R.id.iv_customer_credit})
    public void onViewClicked(View view) {
        mPresenter.onViewClick(view.getId(), type);
    }

}
